/*
 * @Author: your name
 * @Date: 2021-05-17 10:36:28
 * @LastEditTime: 2021-07-21 13:44:38
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \dolphin-data-center-front-end\src\utils\util.js
 */
import enquireJs from 'enquire.js'
import { getOSSConfig } from '@/services/os'

export function isDef(v) {
  return v !== undefined && v !== null
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

export function isRegExp(v) {
  return _toString.call(v) === '[object RegExp]'
}

export function enquireScreen(call) {
  const handler = {
    match: function() {
      call && call(true)
    },
    unmatch: function() {
      call && call(false)
    },
  }
  enquireJs.register('only screen and (max-width: 767.99px)', handler)
}
/**
 * @description:时间格式转换
 * @param {
 * time：{string} 时间戳，
 * type：{number} 0：年月日，1：时分秒，2：年月日-时分秒
 * }
 * @return {*}
 */
export function transferDate(time, type) {
  if (time) {
    var date = new Date(time + 8 * 3600 * 1000)
    //年月日 时分秒(0, 19)  年月日(0,10)  时分秒(11,8)
    let config = [
      [0, 11, 0],
      [10, 8, 19],
    ]
    return date
      .toJSON()
      .substr(config[0][type], config[1][type])
      .replace('T', ' ')
      .replace(/-/g, '-')
  } else {
    return time
  }
}
// 时间戳转时间格式
export function time(time = +new Date()) {
  var date = new Date(time + 8 * 3600 * 1000) // 增加8小时
  return date
    .toJSON()
    .substr(0, 19)
    .replace('T', ' ')
}
export var storage = {
  //存储
  set(key, value) {
    localStorage.setItem(key, JSON.stringify(value))
  },
  //取出数据
  get(key) {
    return JSON.parse(localStorage.getItem(key))
  },
  // 删除数据
  remove(key) {
    localStorage.removeItem(key)
  },
}
// 上传到阿里云
export function upLoadAliyun(param) {
  let _this = this
  // 类型兼容
  let data = param.name ? param.name : param.file.name
  // console.log('param', param, data)
  // 根据资源后缀判断type类型
  // 1.图片 2.视频 3.合同文件 4.音频
  let typeFormat = {
    1: ['jpg', 'png', 'jpeg', 'gif', 'heic', 'webp'],
    2: ['mp4', 'avi'],
    3: ['pdf'],
    4: ['amr', 'wav', 'aac', 'mp3', 'm4a'],
    5: ['xls', 'xlsx'],
  }
  let type = null
  for (let key in typeFormat) {
    typeFormat[key].includes(data.split('.')[data.split('.').length - 1]) &&
      (type = key)
  }
  // console.log('type', type)
  return new Promise((resolve, reject) => {
    getOSSConfig({
      type,
    }).then((res) => {
      let {
        bucket,
        accessEndpoint,
        accessKeyId,
        accessKeySecret,
        region,
        stsToken,
        targetDir,
      } = res.data.data.oss

      var client = new window.OSS({
        bucket,
        accessKeyId,
        accessKeySecret,
        region,
        stsToken,
      })
      // 文件重命名
      let reName = `${new Date().getTime()}-${
        Math.random()
          .toString()
          .split('.')[1]
      }.${data.split('.')[data.split('.').length - 1]}`
      client
        .multipartUpload(`${targetDir}/${reName}`, param.raw || param.file)
        .then((result) => {
          result.filePath = `${accessEndpoint}${targetDir}/${reName}`
          // console.log('result.filePath', result.filePath)
          resolve(result)
        })
        .catch((err) => {
          reject(err)
        })
    })
  })
}
export function getAge(strAge) {
  var birArr = strAge.split('-')
  var birYear = birArr[0]
  var birMonth = birArr[1]
  var birDay = birArr[2]

  d = new Date()
  var nowYear = d.getFullYear()
  var nowMonth = d.getMonth() + 1 //记得加1
  var nowDay = d.getDate()
  var returnAge

  if (birArr == null) {
    return false
  }
  var d = new Date(birYear, birMonth - 1, birDay)
  if (
    d.getFullYear() == birYear &&
    d.getMonth() + 1 == birMonth &&
    d.getDate() == birDay
  ) {
    if (nowYear == birYear) {
      returnAge = 0 //
    } else {
      var ageDiff = nowYear - birYear //
      if (ageDiff > 0) {
        if (nowMonth == birMonth) {
          var dayDiff = nowDay - birDay //
          if (dayDiff < 0) {
            returnAge = ageDiff - 1
          } else {
            returnAge = ageDiff
          }
        } else {
          var monthDiff = nowMonth - birMonth //
          if (monthDiff < 0) {
            returnAge = ageDiff - 1
          } else {
            returnAge = ageDiff
          }
        }
      } else {
        return '出生日期晚于今天，数据有误' //返回-1 表示出生日期输入错误 晚于今天
      }
    }
    return returnAge
  } else {
    return '输入的日期格式错误！'
  }
}

/**
 * @description: 判断参数为空的函数封装
 * @param {*}
 * @return {*}
 */
export function isEmpty(a) {
  /* 检验空字符串 */
  if (a === '') return true
  /* 检验字符串类型的null */
  if (a === 'null') return true
  /* 检验字符串类型的 undefined	*/
  if (a === 'undefined') return true
  /* 检验 undefined 和 null */
  if (!a && a !== 0 && a !== '') return true
  /* 检验空数组	*/
  if (a.length === 0) return true
  /* 检验空对象  */
  if (Object.keys(a).length === 0) return true
  return false
}

/**
 * @description: 删除对象某一属性
 * @param {*}
 * @return {*}
 */
export function del(obj, keys) {
  keys.map(function(key) {
    delete obj[key]
  })
  return obj
}

/**
 * @description: 金额千位分割符号
 * @param {*}
 * @return {*}
 */
export function splitK(num) {
  var decimal = String(num).split('.')[1] || '' //小数部分
  var tempArr = []
  var revNumArr = String(num)
    .split('.')[0]
    .split('')
    .reverse() //倒序
  for (let i in revNumArr) {
    tempArr.push(revNumArr[i])
    if ((i + 1) % 3 === 0 && i != revNumArr.length - 1) {
      tempArr.push(',')
    }
  }
  var zs = tempArr.reverse().join('') //整数部分
  return decimal ? zs + '.' + decimal : zs
}
// 导出
export function exportFile(method = 'post', url, name = '', suffix) {
  const req = new XMLHttpRequest()
  req.open(method, url, true)
  req.responseType = 'blob'
  req.setRequestHeader('Content-Type', 'application/json')
  req.onload = function() {
    const data = req.response
    const a = document.createElement('a')
    const blob = new Blob([data], { type: 'application/octet-stream' })
    let href = window.URL.createObjectURL(blob) //创建下载的链接
    a.href = href
    a.download = `${name}.${suffix}` //下载后文件名
    document.body.appendChild(a)
    a.click() //点击下载
    document.body.removeChild(a) //下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }
  req.send('{}')
}
/**
 * @description: 正则验证
 * @param {*}
 * @return {*}
 */
export var regTest = {
  //15位身份证号
  idCardFifteen(idCard) {
    var reg = /^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/
    return reg.test(Number(idCard))
  },
  //18位身份证号
  idCardEighteen(idCard) {
    var reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    return reg.test(Number(idCard))
  },
  // 手机号
  mobileReg(mobile) {
    // var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    var reg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/ // 最新手机正则
    return reg.test(Number(mobile))
  },
  // 邮箱号
  emailReg(val) {
    var reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
    return reg.test(val)
  },
}
export function isNumber(val) {
  var regPos = /^\d+(\.\d+)?$/ //非负浮点数
  var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/ //负浮点数
  if (regPos.test(val) || regNeg.test(val)) {
    return true
  } else {
    return false
  }
}

/**
 * @description: 年月日转时间戳
 * @param {*}
 * @return {*}
 */
export function dateToTimestamp(dateStr) {
  if (!dateStr) {
    return ''
  } else {
    if (String(dateStr).indexOf('-') == -1) {
      return dateStr
    }
  }
  let newDataStr = dateStr.replace(/\.|-/g, '/')
  let date = new Date(newDataStr)
  let timestamp = date.getTime()
  return timestamp
}

/**
 * @description: 通过身份证取出出生年月日
 * @param {*}
 * @return {*}
 */
export function getBirthdayFromIdCard(idCard) {
  var birthday = ''
  if (idCard != null && idCard != '') {
    if (idCard.length == 15) {
      birthday = '19' + idCard.substr(6, 6)
    } else if (idCard.length == 18) {
      birthday = idCard.substr(6, 8)
    }

    birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-')
  }

  return birthday
}
/**
 * @description: 对象转为数组
 * @param {*}
 * @return {*}
 */
export function getObjToArray(arr1, arr2, obj) {
  var arr = []
  for (var key in obj) {
    var temp = {}
    const txt = arr1[arr2.findIndex((item) => item == key)]
    if (txt) {
      temp.txt = txt
      temp.value = obj[key]
      arr.push(temp)
    }
  }
  return arr
}

const _toString = Object.prototype.toString
